﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using _80X_CG_Frame.Objects;
using _80X_CG_Frame.Windows;
using _80X_CG_Frame.Workers;
using MahApps.Metro.Controls;

namespace _80X_CG_Frame
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        DisposeWorker disposeWorker;
        Config configWindow;
        public MainWindow()
        {
            InitializeComponent();
            BindControls();
            if(GLOBAL.config.Get("auto_start") == "是")
                SwitchRunAsync();
        }
        private void BindControls()
        {
            log_textbox.SetBinding(TextBox.DataContextProperty, new Binding { Source = Log.logWorker, Path = new PropertyPath("Log_stack"), Mode = BindingMode.OneWay });
            trayCode_info.SetBinding(TextBox.DataContextProperty, new Binding { Source = GLOBAL.下料位状态, Path = new PropertyPath("Barcode"), Mode = BindingMode.OneWay });
            CG_info.SetBinding(TextBox.DataContextProperty, new Binding { Source = GLOBAL.下料位状态.Product, Path = new PropertyPath("Barcode"), Mode = BindingMode.OneWay });
            CG_code_ok.SetBinding(TextBox.DataContextProperty, new Binding { Source = GLOBAL.统计数据, Path = new PropertyPath("下CG_Count_OK"), Mode = BindingMode.OneWay });
            CG_code_ng.SetBinding(TextBox.DataContextProperty, new Binding { Source = GLOBAL.统计数据, Path = new PropertyPath("下CG_Count_NG"), Mode = BindingMode.OneWay });
            上CG_info.SetBinding(TextBox.DataContextProperty, new Binding { Source = GLOBAL.统计数据, Path = new PropertyPath("上CG_Barcode"), Mode = BindingMode.OneWay });
            上CG_code_ok.SetBinding(TextBox.DataContextProperty, new Binding { Source = GLOBAL.统计数据, Path = new PropertyPath("上CG_Count_OK"), Mode = BindingMode.OneWay });
            上CG_code_ng.SetBinding(TextBox.DataContextProperty, new Binding { Source = GLOBAL.统计数据, Path = new PropertyPath("上CG_Count_NG"), Mode = BindingMode.OneWay });
            start_time.SetBinding(TextBox.DataContextProperty, new Binding { Source = GLOBAL.统计数据, Path = new PropertyPath("运行时间"), Mode = BindingMode.OneWay });
            round_times.SetBinding(TextBox.DataContextProperty, new Binding { Source = GLOBAL.统计数据, Path = new PropertyPath("回环线动作数"), Mode = BindingMode.OneWay });
            average_time.SetBinding(TextBox.DataContextProperty, new Binding { Source = GLOBAL.统计数据, Path = new PropertyPath("回环线动作平均时间"), Mode = BindingMode.OneWay });

            相机视觉_switch.SetBinding(ToggleSwitchButton.DataContextProperty, new Binding {Source = GLOBAL.cameras, Path = new PropertyPath("IsConnect") });
            PLC_switch.SetBinding(ToggleSwitchButton.DataContextProperty, new Binding { Source = GLOBAL.plc, Path = new PropertyPath("IsConnect") });
            SFC服务器_switch.SetBinding(ToggleSwitchButton.DataContextProperty, new Binding { Source = GLOBAL.logUpload, Path = new PropertyPath("IsConnect") });
            激光机台1_switch.SetBinding(ToggleSwitchButton.DataContextProperty, new Binding { Source = GLOBAL.laser["激光机台1"], Path = new PropertyPath("IsConnect") });
            激光机台2_switch.SetBinding(ToggleSwitchButton.DataContextProperty, new Binding { Source = GLOBAL.laser["激光机台2"], Path = new PropertyPath("IsConnect") });
            //激光机台3_switch.SetBinding(ToggleSwitchButton.DataContextProperty, new Binding { Source = GLOBAL.laser["激光机台3"], Path = new PropertyPath("IsConnect") });
            扫码枪1_switch.SetBinding(ToggleSwitchButton.DataContextProperty, new Binding { Source = GLOBAL.扫码枪["扫码枪1"], Path = new PropertyPath("IsConnect") });
            扫码枪2_switch.SetBinding(ToggleSwitchButton.DataContextProperty, new Binding { Source = GLOBAL.扫码枪["扫码枪2"], Path = new PropertyPath("IsConnect") });
            机器手1_switch.SetBinding(ToggleSwitchButton.DataContextProperty, new Binding { Source = GLOBAL.robot["机器手1"], Path = new PropertyPath("IsConnect") });
            机器手2_switch.SetBinding(ToggleSwitchButton.DataContextProperty, new Binding { Source = GLOBAL.robot["机器手2"], Path = new PropertyPath("IsConnect") });
        }
        /// <summary>
        /// 工作线程启动
        /// </summary>
        /// <returns></returns>
        private async Task SwitchRunAsync()
        {
            start_stop.IsEnabled = false;
            if (disposeWorker == null)
            {
                start_stop.Header = "停止";
                disposeWorker = new DisposeWorker();
            }
            else if (disposeWorker != null)
            {
                start_stop.Header = "启动";
                await disposeWorker.DisposeAsync();
                disposeWorker = null;
            }
            start_stop.IsEnabled = true;
        }
        /// <summary>
        /// 相机连接开关
        /// </summary>
        /// <param name="toggle_switch"></param>
        /// <returns></returns>
        private async Task SwitchCameraAsync(ToggleSwitchButton toggle_switch)
        {
            toggle_switch.IsEnabled = false;
            if (!GLOBAL.cameras.IsConnect)
            {
                if (await GLOBAL.cameras.CamConnectAsync(GLOBAL.config.Get("相机视觉_address")))
                    Log.Write("相机视觉连接成功");
                else
                    Log.Write("相机视觉连接失败");
            }
            else
            {
                GLOBAL.cameras.DisConnect();
                Log.Write("相机视觉连接断开");
            }
            toggle_switch.IsEnabled = true;
        }
        /// <summary>
        /// 日志上传连接开关
        /// </summary>
        /// <param name="toggle_switch"></param>
        /// <returns></returns>
        private async Task SwitchSFCAsync(ToggleSwitchButton toggle_switch)
        {
            toggle_switch.IsEnabled = false;
            if (!GLOBAL.logUpload.IsConnect)
            {
                if (await GLOBAL.logUpload.ConnectAsync(GLOBAL.config.Get("SFC服务器_address")))
                    Log.Write("SFC服务器连接成功");
                else
                    Log.Write("SFC服务器连接失败");
            }
            else
            {
                GLOBAL.logUpload.DisConnect();
                Log.Write("SFC服务器连接断开");
            }
            toggle_switch.IsEnabled = true;
        }
        /// <summary>
        /// PLC连接开关
        /// </summary>
        /// <param name="toggle_switch"></param>
        /// <returns></returns>
        private async Task SwitchPLCAsync(ToggleSwitchButton toggle_switch)
        {
            toggle_switch.IsEnabled = false;
            if (!GLOBAL.plc.IsConnect)
            {
                //连接PLC
                string plc_address = GLOBAL.config.Get("PLC_address");
                //int plc_port = Convert.ToInt32(GLOBAL.config.Get("PLC_port"));
                if (await GLOBAL.plc.ConnectAsync(plc_address))
                    Log.Write("PLC连接成功");
                else
                    Log.Write("PLC连接失败");
            }
            else
            {
                GLOBAL.plc.Disconnect();
                Log.Write("PLC连接断开");
            }
            toggle_switch.IsEnabled = true;
        }
        /// <summary>
        /// 激光机台连接开关
        /// </summary>
        /// <param name="laser_name"></param>
        /// <param name="toggle_switch"></param>
        /// <returns></returns>
        private async Task SwitchLaserAsync(ToggleSwitchButton toggle_switch)
        {
            string laser_name = toggle_switch.Name.Split('_')[0];
            toggle_switch.IsEnabled = false;
            if (!GLOBAL.laser[laser_name].IsConnect)
            {
                //连接PLC
                string laser_address = GLOBAL.config.Get(laser_name + "_address");
                //int laser_port = Convert.ToInt32(GLOBAL.config.Get(laser_name + "_port"));
                if (await GLOBAL.laser[laser_name].ConnectAsync(laser_address))
                    Log.Write(laser_name + "连接成功");
                else
                    Log.Write(laser_name + "连接失败");
            }
            else
            {
                GLOBAL.laser[laser_name].DisConnect();
                Log.Write(laser_name + "连接断开");
            }
            toggle_switch.IsEnabled = true;
        }
        /// <summary>
        /// 扫码枪连接开关
        /// </summary>
        /// <param name="toggle_switch"></param>
        /// <returns></returns>
        private async Task Switch扫码枪Async(ToggleSwitchButton toggle_switch)
        {
            toggle_switch.IsEnabled = false;
            string 扫码枪_name = toggle_switch.Name.Split('_')[0];
            if (!GLOBAL.扫码枪[扫码枪_name].IsConnect)
            {
                string 扫码枪_address = GLOBAL.config.Get(扫码枪_name + "_address");
                if (await GLOBAL.扫码枪[扫码枪_name].ConnectAsync(扫码枪_address))
                    Log.Write(扫码枪_name+"连接成功");
                else
                    Log.Write(扫码枪_name+"连接失败");
            }
            else
            {
                GLOBAL.扫码枪[扫码枪_name].DisConnect();
                Log.Write(扫码枪_name+"连接断开");
            }
            toggle_switch.IsEnabled = true;
        }
        /// <summary>
        /// 机械手连接开关
        /// </summary>
        /// <param name="robot_name"></param>
        /// <param name="toggle_switch"></param>
        /// <returns></returns>
        private async Task SwitchRobotAsync(ToggleSwitchButton toggle_switch)
        {
            string robot_name = toggle_switch.Name.Split('_')[0];
           toggle_switch.IsEnabled = false;
            if (!GLOBAL.robot[robot_name].IsConnect)
            {
                //连接机械手
                string robot_address = GLOBAL.config.Get(robot_name + "_address");
                //int laser_port = Convert.ToInt32(GLOBAL.config.Get(robot_name + "_port"));
                if (await GLOBAL.robot[robot_name].ConnectAsync(robot_address))
                    Log.Write(robot_name + "连接成功");
                else
                    Log.Write(robot_name + "连接失败");
            }
            else
            {
                GLOBAL.robot[robot_name].DisConnect();
                Log.Write(robot_name + "连接断开");
            }
            toggle_switch.IsEnabled = true;
        }

        private void start_stop_button_Click(object sender, RoutedEventArgs e) => SwitchRunAsync();

        private void switch_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) => ((ToggleSwitchButton)sender).IsChecked = (bool)e.NewValue;

        private void cameras_switch_Click(object sender, RoutedEventArgs e) => SwitchCameraAsync((ToggleSwitchButton)sender);

        private void PLC_switch_Click(object sender, RoutedEventArgs e) => SwitchPLCAsync((ToggleSwitchButton)sender);

        private void start_stop_Click(object sender, RoutedEventArgs e) => SwitchRunAsync();

        private void laser_switch_Click(object sender, RoutedEventArgs e) => SwitchLaserAsync((ToggleSwitchButton)sender);

        private void Expander_Expanded(object sender, RoutedEventArgs e)
        {
            Panel.SetZIndex(log_grid, 2);
             //splitter_log.Visibility = Visibility.Visible;
        }

        private void Expander_Collapsed(object sender, RoutedEventArgs e)
        {
            Panel.SetZIndex(log_grid, 0);
            //splitter_log.Visibility = Visibility.Collapsed;
        }

        private void log_textbox_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (log_textbox.Text.Length > 65535)
                log_textbox.Clear();
            log_textbox.AppendText((string)e.NewValue);
            log_textbox.ScrollToEnd();
        }

        

        private void 扫码枪_switch_Click(object sender, RoutedEventArgs e) =>Switch扫码枪Async((ToggleSwitchButton)sender);

        private void SFC_switch_Click(object sender, RoutedEventArgs e) => SwitchSFCAsync((ToggleSwitchButton)sender);

        private void robot_switch_Click(object sender, RoutedEventArgs e) => SwitchRobotAsync((ToggleSwitchButton)sender);

        private void open_config(object sender, RoutedEventArgs e)
        {
            if (configWindow == null)
                configWindow = new Config();
            if (configWindow != null)
            {
                configWindow.Show();
                configWindow.Focus();
            }
        }

        private void open_log_Click(object sender, RoutedEventArgs e) => System.Diagnostics.Process.Start(Log.LogPath());

        private void MetroWindow_Closed(object sender, EventArgs e)
        {
            if (configWindow != null)
                configWindow.RealClose();
        }

        private void laser_get_test_LostFocus(object sender, RoutedEventArgs e)
        {
            //Dictionary<string,string> dic =  LaserEngine.GetLaserConfigs(laser_get_test.Text);
            //foreach(KeyValuePair<string,string> kvp in dic)
            //{
            //    Log.Write(kvp.Key + ":" + kvp.Value);
            //}
        }

        private void camera_test_get_LostFocus(object sender, RoutedEventArgs e)
        {
        }

        private void CG_info_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            CG_info.Text = e.NewValue.ToString();
        }

        private void tray_info_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            trayCode_info.Text = e.NewValue.ToString();
        }

        private void CG_code_ok_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            CG_code_ok.Text = e.NewValue.ToString();
        }

        private void CG_code_ng_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            CG_code_ng.Text = e.NewValue.ToString();
        }

        private void start_time_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var t = (TimeSpan)e.NewValue;
            start_time.Text = t.Days + "天" + t.Hours + ":" + t.Minutes + ":" + t.Seconds;
        }

        private void round_times_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            round_times.Text = e.NewValue.ToString();

        }

        private void average_time_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            average_time.Text = ((TimeSpan)(e.NewValue)).TotalSeconds + "秒";

        }

        private void clear_btn_Click(object sender, RoutedEventArgs e)
        {
            CG_code_ok.Text = 0.ToString();
            CG_code_ng.Text = 0.ToString();
        }

        private void 上CG_info_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            上CG_info.Text = e.NewValue.ToString();
        }

        private void 上CG_code_ok_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            上CG_code_ok.Text = e.NewValue.ToString();
        }

        private void 上CG_code_ng_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            上CG_code_ng.Text = e.NewValue.ToString();
        }

        private void 上cg_clear_btn_Click(object sender, RoutedEventArgs e)
        {
            上CG_code_ok.Text = 0.ToString();
            上CG_code_ng.Text = 0.ToString();
        }
    }
}
